package com.insight.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.service.*;
import com.yuanqiao.insight.acore.depart.entity.SysDepart;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import org.apache.commons.lang3.StringUtils;
import com.insight.modules.constant.CommonConstant;
import org.insight.modules.system.entity.*;
import org.insight.modules.system.service.*;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.api.ISysBaseAPI;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.system.vo.SysDepartModel;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.mapper.SysUserDepartMapper;
import com.insight.modules.system.mapper.SysUserMapper;
import com.insight.modules.system.model.DepartIdModel;
import com.insight.modules.system.service.*;
import com.insight.modules.system.vo.SysUserDepVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <P>
 * 用户部门表实现类
 * <p/>
 * @Author ZhiLin
 *@since 2019-02-22
 */
@Service
public class SysUserDepartServiceImpl extends ServiceImpl<SysUserDepartMapper, SysUserDepart> implements ISysUserDepartService {

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ISysRolePermissionService sysRolePermissionService;
	@Autowired
	private ISysPermissionService sysPermissionService;
	@Autowired
	private SysUserDepartMapper sysUserDepartMapper;
	@Autowired
	private SysUserMapper sysUserMapper;

	/**
	 * 根据用户ID查询该用户所属部门信息列表
	 * @param userId 用户ID
	 * @return List<DepartIdModel> 部门信息模型列表，可能为空
	 */
	@Override
	public List<DepartIdModel> queryDepartIdsOfUser(String userId) {
		// 构造查询条件，查询用户与部门的关联关系
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<SysDepart> queryDep = new LambdaQueryWrapper<>();

		queryUDep.eq(SysUserDepart::getUserId, userId); // 根据用户ID过滤

		List<String> depIdList = new ArrayList<>();   // 存放部门ID列表
		List<DepartIdModel> depIdModelList = new ArrayList<>(); // 最终返回结果

		List<SysUserDepart> userDepList = this.list(queryUDep); // 查询用户部门关联数据
		if (userDepList != null && !userDepList.isEmpty()) {
			// 收集所有部门ID
			for (SysUserDepart userDepart : userDepList) {
				depIdList.add(userDepart.getDepId());
			}
			// 查询部门详细信息
			queryDep.in(SysDepart::getId, depIdList);
			List<SysDepart> depList = sysDepartService.list(queryDep);
			if (depList != null && !depList.isEmpty()) {
				// 转换为返回模型
				for (SysDepart depart : depList) {
					depIdModelList.add(new DepartIdModel().convertByUserDepart(depart));
				}
			}
			return depIdModelList;
		}

		return null;
	}

	/**
	 * 根据部门ID查询部门下所有用户列表
	 * @param depId 部门ID
	 * @return List<SysUsers> 用户列表，密码和盐字段已清空
	 */
	@Override
	public List<SysUsers> queryUserByDepId(String depId) {
		// 构建查询条件，查询用户部门关联数据
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<>();
		queryUDep.eq(SysUserDepart::getDepId, depId);

		List<String> userIdList = new ArrayList<>();
		List<SysUserDepart> uDepList = this.list(queryUDep);

		if (uDepList != null && !uDepList.isEmpty()) {
			// 收集所有用户ID
			for (SysUserDepart uDep : uDepList) {
				userIdList.add(uDep.getUserId());
			}
			// 根据用户ID批量查询用户信息
			List<SysUsers> userList = (List<SysUsers>) sysUserService.listByIds(userIdList);

			// 清理密码相关敏感信息，避免暴露
			for (SysUsers sysUser : userList) {
				sysUser.setSalt("");
				sysUser.setPassword("");
			}
			return userList;
		}
		return new ArrayList<>();
	}

	/**
	 * 根据部门编码（含子部门）查询用户
	 * 支持按用户名模糊查询和权限过滤（flag=1时）
	 * @param depCode 部门编码，支持模糊查询
	 * @param realname 用户真实姓名，模糊匹配
	 * @param flag 过滤标志，1时只返回有“帮助管理”权限的用户
	 * @return List<SysUsers> 用户列表，密码和盐字段已清空
	 */
	@Override
	public List<SysUsers> queryUserByDepCode(String depCode, String realname, Integer flag) {
		// 查询当前部门及所有下级部门
		LambdaQueryWrapper<SysDepart> queryByDepCode = new LambdaQueryWrapper<>();
		queryByDepCode.likeRight(SysDepart::getOrgCode, depCode);
		List<SysDepart> sysDepartList = sysDepartService.list(queryByDepCode);

		List<String> depIds = sysDepartList.stream().map(SysDepart::getId).collect(Collectors.toList());

		// 根据部门ID列表查询用户部门关联数据
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<>();
		queryUDep.in(SysUserDepart::getDepId, depIds);

		List<String> userIdList = new ArrayList<>();
		List<SysUserDepart> uDepList = this.list(queryUDep);

		if (uDepList != null && !uDepList.isEmpty()) {
			// 收集所有用户ID
			for (SysUserDepart uDep : uDepList) {
				userIdList.add(uDep.getUserId());
			}

			// 构造用户查询条件
			LambdaQueryWrapper<SysUsers> queryUser = new LambdaQueryWrapper<>();
			queryUser.in(SysUsers::getId, userIdList);

			if (oConvertUtils.isNotEmpty(realname)) {
				queryUser.like(SysUsers::getRealname, realname.trim());
			}

			// 查询用户列表
			List<SysUsers> userList = (List<SysUsers>) sysUserService.list(queryUser);

			ArrayList<SysUsers> list = new ArrayList<>();

			for (SysUsers sysUser : userList) {
				// 清空敏感字段
				sysUser.setSalt("");
				sysUser.setPassword("");

				// 如果flag=1，过滤没有“帮助管理”权限的用户
				if (flag != null && flag == 1) {
					// 查询用户角色
					SysUserRole userRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));

					// 查询角色权限
					List<SysRolePermission> rolePermissionList = sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().eq("role_id", userRole.getRoleId()));

					// 收集权限ID列表
					List<String> permissionIdList = rolePermissionList.stream()
							.map(SysRolePermission::getPermissionId).collect(Collectors.toList());

					// 查询“帮助管理”权限ID
					String helpManageId = sysPermissionService.getOne(new QueryWrapper<SysPermission>().eq("name", "帮助管理")).getId();

					// 如果没有权限，则跳过该用户
					if (!permissionIdList.contains(helpManageId)) {
						continue;
					}
				}
				list.add(sysUser);
			}
			return list;
		}
		return new ArrayList<>();
	}

	// 后续其他方法也可参考以上注释风格进行补充

}

